package com.egobuy.controller;

import com.egobuy.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.UUID;

@RestController
@RequestMapping("egobuy")
@CrossOrigin(allowedHeaders = "*",value = "*",origins = "*",methods = {RequestMethod.GET,RequestMethod.POST},maxAge = 3600)
public class FileController {
    // 注入文件的存储位置
    @Value("${file-sever.base-path}")
    private String basePath;

    @Value("${server.port}")
    private int port;
    @Value("${server.servlet.context-path}")
    private String contentPath;

    @RequestMapping(value = ("/upload"),produces = "application/json;charset=utf-8")
    public BuyResult upload(@RequestParam("uploadFile")MultipartFile uploadFile) throws UnknownHostException {
        BuyResult result=BuyResult.ok();
        //处理文件上传
        // 给文件生成物理名称
        String fileName=uploadFile.getOriginalFilename();
        //截取
        String ext=fileName.substring(fileName.indexOf("."));
        // 按照日期准备文件夹。 一天一个文件夹。
        Calendar c = Calendar.getInstance();
        String dirName = c.get(Calendar.YEAR)+""+(c.get(Calendar.MONTH)+1)+""+c.get(Calendar.DATE);
        File dir=new File(basePath,dirName);
        if (!dir.exists() || !dir.isDirectory()){
            dir.mkdir();
        }
        // 准备文件
        File targetFile = null;
        while (true){
            fileName=System.currentTimeMillis()+"_"+ UUID.randomUUID()+ext;
            targetFile=new File(dir,fileName);
            if (!targetFile.exists()){
                break;
            }
        }
        try {
            uploadFile.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 添加图片的访问地址
        // 获取本机的ip地址
        String ipAddr= InetAddress.getLocalHost().getHostAddress();
        //System.out.println("IP地址："+ipAddr);

        //
        String msg="http://192.168.66.1"+contentPath+":"+port+"/"+dir.getName()+"/"+fileName;

        result.setMsg(msg);
        return result;

    }
}
